package com.scau.service.impl;

import com.scau.common.exception.BusinessException;
import com.scau.dao.ContractDao;
import com.scau.dao.StudentDao;
import com.scau.entity.Contract;
import com.scau.entity.Student;
import com.scau.service.ContractService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ContractServiceImpl implements ContractService {

    @Autowired
    private ContractDao contractDao;
    @Autowired
    private StudentDao studentDao;

    @Transactional
    @Override
    public void add(Contract contract) {

        Student student = studentDao.findOne(contract.getStudentId());
        contract.setAge(student.getAge());
        contract.setGender(student.getGender());
        contract.setBirth(student.getBirth());
        contract.setPhone(student.getPhone());
        contract.setLinkman(student.getLinkman());
        Contract cache = contractDao.save(contract);

        BeanUtils.copyProperties(cache, contract);

        student.setPoints(student.getPoints() + cache.getPoints());
        student.setRemainingClass(student.getRemainingClass() + cache.getRemainingClass());

        studentDao.save(student);
    }

    @Override
    public Contract findOne(Long contractId) {
        Contract contract = contractDao.findOne(contractId);

        if (contract == null) {
            throw new BusinessException("不存在该合同");
        }
        return contract;
    }

    @Override
    public Page<Contract> findAll(Contract contract, Pageable pageable) {
        return contractDao.findAll(Example.of(contract), pageable);
    }

}
